/*
* BlackList
* Reads from file a list of websites to be blocked
* If a website is found in the BlackList then its content will be blocked
*
* Cassie Chin, Stephen Smetana, Logan Widick
* CSCE 3530 Program 2
*/


#include "blacklist.h"


void printBlacklist(Blacklisted * blackListHead)
{
    Blacklisted * tempPtr = blackListHead;
    while(tempPtr != NULL)
    {
        printf("%s\n", tempPtr->url);
        tempPtr = tempPtr->ptr2next;
    }
}


int isThisBlacklisted(Blacklisted * blackListHead, char * userString)
{
    Blacklisted * tempPtr = blackListHead;
    while(tempPtr != NULL)
    {
       if (strcasestr(userString, tempPtr->url) != NULL ) return 1;
       tempPtr = tempPtr->ptr2next;
    }
    return 0; // 0 for not in Blacklist
}

Blacklisted *new_Blacklisted(FILE *file_input)
{

    file_input = fopen ("blacklist.txt", "r");
    if (file_input == NULL) printf(" Error! blacklist.txt not found! \n");

    Blacklisted * blackListHead = NULL;
    Blacklisted * tempPtr;
    char tempString[1000];

    // Get each line from the file until EOF
    while ( fgets (tempString , 1000 , file_input) != NULL )
    {
        if (isThisBlacklisted(blackListHead, tempString)) continue; // if the url is already in the list, then dont add it again.
        // Allocate Memory for each url in the list
        Blacklisted *newBlack = (Blacklisted *) calloc(1, sizeof(Blacklisted));
        newBlack->url = (char *) calloc(50, sizeof(char));
        // this removes the "/" at the end of the url
		tempString[strlen(tempString)-2] = '\0';
        // Copy the line from file, into the new list element
        strcpy(newBlack->url,tempString);

        // If head is null, then make this element the new head
        if (blackListHead == NULL)
            blackListHead = newBlack;
        // Else find the last node, and have it point to this new element
        else
        {
            tempPtr = blackListHead;
            while(tempPtr != NULL)
            {
                if (tempPtr->ptr2next == NULL)
                {
                    tempPtr->ptr2next = newBlack;
                    break;
                }
                tempPtr = tempPtr->ptr2next;
            }
        } // end else
    }// end while

    // Test function, we can use this later to allow a user to see what websites are blocked
    //printBlacklist(blackListHead);

    // We will use isThisBlacklisted to see if a website can be loaded into the proxy
    // The following are examples of what will successfully find a black listed website
    // These 3 cases will all work when the url in the list is "https://www.google.com"
    //if (isThisBlacklisted(blackListHead, "https://www.google.com")) printf("Blacklisted\n");
    //if (isThisBlacklisted(blackListHead, "www.google.com")) printf("Blacklisted\n");
    //if (isThisBlacklisted(blackListHead, "google.com")) printf("Blacklisted\n");

    // close the file
    fclose(file_input);
	return blackListHead;
} // end main

